# -*- coding: utf-8 -*-
'''
Created on 2012-4-19

@author: deadblue
'''
import time
import cookielib

class Cookie:
    ''' 仅支持早期RFC标准的Cookie '''

    def __init__(self, raw=None):
        # cookie基本属性
        self.name = ''
        self.value = ''
        self.domain = None
        self.path = None
        self.expires = -1
        # 解析传入的cookie串
        if raw is not None: self._parse_raw(raw)

    def _parse_raw(self, raw):
        if raw is None: return
        attrs = raw.split('; ')
        # 处理名称和值
        self.name, self.value = attrs[0].split('=')
        # 处理其他属性
        attr_dic = {'domain':None, 'path':None, 'expired':0}
        for i in range(1, len(attrs)):
            attr = attrs[i]
            if attr.find('=') < 0:
                k, v = attr, None
            else:
                k, v = attr.split('=')
            if k == 'expired':
                v = cookielib.http2time(v)
            attr_dic[k] = v
        # 保存属性
        self.domain = attr_dic['domain']
        self.path = attr_dic['path']
        self.expires = attr_dic['expired']

    def is_expires(self):
        return time.time() < self.expires

    def to_header_string(self):
        return '%s=%s' % (self.name, self.value)


class CookieJar:
    def __init__(self):
        self.cookies = dict()

    def add_raw_cookies(self, raw):
        # 分割并重新组合cookie
        cks = raw.split(', ')
        index = 0
        while index < len(cks):
            ck = cks[index]
            if ck.find('=') < 0 or (ck.find('=') > ck.find(';')):
                cks[index-1] = '%s, %s' % (cks[index-1], ck)
                del cks[index]
                index -= 1
            index += 1
        # 将解析出的cookie保存起来
        for ck in cks: self.add_cookie(Cookie(ck))

    def add_cookie(self, cookie):
        ''' 添加cookie '''
        if cookie is None: return
        self.cookies.update({cookie.name: cookie})

    def size(self):
        return len(self.cookies)

    def to_header_string(self):
        ''' 生成请求头需要的cookie串 '''
        cks = list()
        for ck in self.cookies.values():
            if not ck.is_expires(): cks.append(ck.to_header_string())
        return '; '.join(cks)
